<template>
  <div style="margin-top: 2vh">
    <div style="background-color: white; width: 68vw; margin: auto;">
      <!-- 上方标题 -->
      <div style="border-bottom: 1px solid #e9e9e9; height: 7vh; width: 100%;">
        <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw;">编辑继续教育信息</span>
        <span style="font-size: 0.8rem; color: #8c8c8c; margin-left: 1vw; line-height: 7vh;">请编辑您的继续教育信息。</span>
      </div>

      <pdf-preview
          ref="pdfPreviewRef"
          :pdf-url="form.pdfPath"
          @update:pdf-path="updatePdfPath"
          @rotations-changed="handleRotationsChanged"
      ></pdf-preview>
    </div>

    <!-- 填写信息 -->
    <div style="background-color: white; width: 68vw; margin: auto; display: flex; flex-direction: column; padding-bottom: 5vh; margin-top: 3vh;margin-bottom: 3vh ">
      <div style="flex: 1;">
        <div style="border-bottom: 1px solid #e9e9e9; height: 7vh;">
          <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw">编辑信息</span>
        </div>
        <div>
          <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" style="margin-top: 5vh">
            <el-form-item label="材料标题" prop="title" required>
              <el-input
                  v-model="form.title"
                  placeholder="请输入材料标题"
                  style="width: 34vw;"
              ></el-input>
            </el-form-item>

            <el-form-item label="培训单位" prop="trainingUnit" required>
              <el-input
                  v-model="form.trainingUnit"
                  placeholder="请输入培训单位"
                  style="width: 34vw;"
              ></el-input>
            </el-form-item>

            <el-form-item label="课时" prop="hours" required>
              <el-input-number
                  v-model="form.hours"
                  :precision="1"
                  :step="0.5"
                  :min="0"
                  style="width: 34vw;"
              ></el-input-number>
            </el-form-item>

            <el-form-item label="评分/等级" prop="score">
              <el-input
                  v-model="form.score"
                  placeholder="如: 80/优"
                  style="width: 34vw;"
              ></el-input>
            </el-form-item>

            <el-form-item label="获得时间" prop="obtainTime" required>
              <el-date-picker
                  v-model="form.obtainTime"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="x"
                  style="width: 34vw;"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="是否同步" prop="syncStatus">
              <el-select v-model="form.syncStatus" style="width: 34vw;" placeholder="请选择是否同步">
                <el-option label="是" :value="'是'"></el-option>
                <el-option label="否" :value="'否'"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关联课题" prop="projectId">
              <el-select v-model="form.projectId" placeholder="请选择本成果所属课题,以便使用结题助手功能" style="width: 34vw;">
                <el-option v-for="project in longitudinalProjects" :key="project.id" :label="project.projectName" :value="project.id">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="备注信息" prop="remarks">
              <el-input
                  type="textarea"
                  v-model="form.remarks"
                  :rows="4"
                  placeholder="请输入备注信息"
                  style="width: 34vw;"
              ></el-input>
            </el-form-item>
          </el-form>

          <div style="display: flex; justify-content: center; margin-top: 2vh">
            <button @click="submitForm" class="upload-button" style="width: 10vw;" :disabled="isSubmitting">
              {{ isSubmitting ? '保存中...' : '保 存' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, watch} from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import PdfPreview from '@/components/PdfPreview.vue'
import { getContinueEducationById, updateContinueEducationMaterial } from "@/api/Manage/continueEducation.js"
import {getCompletedLongitudinal, getProjectNameById} from "@/api/Research/Longitudinal.js"
import { batchUpdatePdfPages } from "@/api/Manage/File.js";

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const pdfPreviewRef = ref(null)
const longitudinalProjects = ref([]) // 存储已完成的纵向课题
const isSubmitting = ref(false) // 提交状态
const hasRotations = ref(false) // 是否有旋转
const currentRotations = ref([]) // 存储当前的旋转信息

// 表单数据
const form = reactive({
  id: '',
  title: '',
  trainingUnit: '',
  hours: 0,
  score: '',
  obtainTime: '',
  remarks: '',
  projectId: '',
  syncStatus: '',
  pdfPath: ''
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入材料标题', trigger: 'blur' }],
  trainingUnit: [{ required: true, message: '请输入培训单位', trigger: 'blur' }],
  hours: [{ required: true, message: '请输入课时', trigger: 'blur' }],
  obtainTime: [{ required: true, message: '请选择获得时间', trigger: 'change' }]
}

const updatePdfPath = (newPath) => {
  form.pdfPath = newPath.firstImageUrl
}

// 处理旋转状态变化
const handleRotationsChanged = (rotations) => {
  hasRotations.value = rotations.length > 0
  currentRotations.value = rotations
  console.log('旋转状态变化:', rotations)
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    isSubmitting.value = true

    // 验证表单
    const valid = await new Promise((resolve) => {
      formRef.value.validate((valid) => resolve(valid))
    })
    if (!valid) {
      ElMessage.error('请填写必填项')
      return
    }

    // 如果有旋转，先保存旋转
    if (hasRotations.value && currentRotations.value.length > 0) {
      try {
        // 组装批量更新请求数据
        const batchData = {
          filePath: form.pdfPath, // PDF文件路径
          pages: currentRotations.value.map(rotation => ({
            pageNumber: rotation.pageIndex + 1, // 页码从1开始
            rotation: rotation.rotation // 旋转角度
          }))
        }

        console.log('批量更新旋转请求数据:', batchData)

        const rotationResult = await batchUpdatePdfPages(batchData)
        console.log('批量更新旋转结果:', rotationResult)

        if (rotationResult.code !== "0") {
          ElMessage.error('保存旋转失败: ' + (rotationResult.message || '未知错误'))
          return
        }

        ElMessage.success('旋转保存成功')

        // 重置旋转状态
        hasRotations.value = false
        currentRotations.value = []

        // 通知PDF预览组件重新加载
        if (pdfPreviewRef.value && pdfPreviewRef.value.reloadPDF) {
          await pdfPreviewRef.value.reloadPDF(form.pdfPath)
        }

      } catch (rotationError) {
        console.error('保存旋转失败:', rotationError)
        ElMessage.error('保存旋转失败: ' + (rotationError.message || '网络错误'))
        return
      }
    }

    // 提交继续教育信息
    const response = await updateContinueEducationMaterial(form)
    if (response.code === 1) {
      ElMessage.success('保存成功')
      router.push('/main/result/ContinueEducation')
    } else {
      ElMessage.error(response.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    isSubmitting.value = false
  }
}

watch(() => form.projectId, async (newProjectId) => {
  if (newProjectId) {
    const projectRes = await getProjectNameById(newProjectId);
    if (projectRes.data) {
      form.projectId = projectRes.data;
    }
  }
});

// 获取详情数据和已完成的纵向课题
onMounted(async () => {
  const id = route.query.id
  if (id) {
    try {
      const res = await getContinueEducationById(id)
      if (res.code === 1 && res.data) {
        const data = res.data
        // 处理日期时间戳
        if (data.obtainTime) {
          data.obtainTime = Number(data.obtainTime)
        }
        Object.assign(form, data)
      } else {
        ElMessage.error('获取继续教育信息失败')
      }
    } catch (error) {
      console.error('获取继续教育信息失败:', error)
      ElMessage.error('获取继续教育信息失败，请重试')
    }
  }

  // 获取已完成的纵向课题
  try {
    const response = await getCompletedLongitudinal()
    if (response.code === 1 && Array.isArray(response.data)) {
      longitudinalProjects.value = response.data
    } else {
      ElMessage.error('获取结题的纵向课题失败')
    }
  } catch (error) {
    console.error('获取结题的纵向课题出错:', error)
    ElMessage.error('获取结题的纵向课题失败，请刷新页面重试')
  }
})
</script>

<style scoped>
.upload-button {
  color: white;
  height: 3.8vh;
  width: 6.5vw;
  background-color: #00b38a;
  cursor: pointer;
  border: none;
}

.upload-button:hover:not(:disabled) {
  background-color: #009b77;
}

.upload-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

canvas {
  display: block;
  margin: 0 auto;
  background: white;
  box-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1);
  transform-origin: top center;
}
</style>
